package edu.ptu.shortlink.project.mq.product;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @BelongsProject: short-link
 * @BelongsPackage: edu.ptu.shortlink.mq
 * @Author: HYJ
 * @CreateTime: 2025-05-16  17:14
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ShortLinkStatsSaveProducer {

    private final RocketMQTemplate rocketMQTemplate;

    @Value("${rocketmq.producer.topic}")
    private String statsSaveTopic;

    public void senMessage(Map<String, String> producerMap) {
        String keys = UUID.randomUUID().toString();

        producerMap.put("keys", keys);
        Message<Map<String, String>> build = MessageBuilder
                .withPayload(producerMap)
                .setHeader(MessageConst.PROPERTY_KEYS, keys)
                .build();

        try {
            SendResult sendResult = rocketMQTemplate.syncSend(statsSaveTopic, build, 2000L);
            log.info("[消息访问统计监控 消息发送结果: {}, 消息ID: {}, 消息Keys: {}]", sendResult.getSendStatus(), sendResult.getMsgId(), keys);
        } catch (Exception e) {
            log.error("[消息服务统计监控] 消息发送失败, 消息体: {}", JSON.toJSONString(producerMap), e);
        }
    }

}
